package com.sec.android.app.myfiles.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.SparseBooleanArray;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.samsung.android.sdk.slinkcloud.CloudGatewaySignInUtils;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.facade.cmd.CopyMoveCmd;
import com.sec.android.app.myfiles.facade.cmd.DeleteRecordCmd;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.feature.MultiWindowMgr;
import com.sec.android.app.myfiles.feature.ViEffectMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.fragment.filelist.FileListFragment;
import com.sec.android.app.myfiles.fragment.home.HomeFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.listener.ListenerMgr;
import com.sec.android.app.myfiles.listener.SystemBroadcastReceiver;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.widget.RclExpansionHelper;

import java.util.ArrayList;

/**
 * Created by daesu83.kim on 2016-05-25.
 */
public class FolderSelectorBottomSheetActivity extends FileListActivity
        implements View.OnClickListener, RclExpansionHelper.OnExpansionStatusListener,
        MultiWindowMgr.StateChangeListener, SystemBroadcastReceiver.OnMediaEject {

    public static final int REQ_CODE_FOLDER_SELECTOR_BOTTOM_SHEET = 20160525;
    public static final String EXTRA_KEY_FOLDER_SELECTOR_BOTTOM_SHEET = "folder_selector_bottom_sheet";
    public static final String EXTRA_KEY_OPERATION = "operation";
    public static final String EXTRA_KEY_STORAGE_TYPE = "storage_type";
    public static final String EXTRA_KEY_DESTINATION_PATH = "dst_path";
    public static final String EXTRA_KEY_NAVIGATION_MODE = "navigation_mode";
    public static final String EXTRA_KEY_FILE_TYPE = "file_type";
    public static final String EXTRA_KEY_CLOUD_FILE_ID = "cloud_file_id";
    public static final String EXTRA_KEY_CLOUD_DEVICE_ID = "cloud_device_id";
    public static final String EXTRA_KEY_CLOUD_PARENT_IDS = "cloud_parent_ids";
    public static final String EXTRA_KEY_START_PATH = AppConstants.MyFilesExtras.EXTRA_START_PATH;
    public static final String EXTRA_KEY_FROM_PRIVATE_BOX = "from_private_box";
    public static final String EXTRA_KEY_FROM_PRIVATE_STORAGE = "from_private_storage";
    public static final String EXTRA_KEY_PREV_SCREEN_PATH = "prev_screen_path";
    public static final String EXTRA_KEY_TOTAL_COUNT = "total_count";

    public static final int RESULT_OK = Activity.RESULT_OK;
    public static final int RESULT_CANCELED = Activity.RESULT_CANCELED;
    public static final int RESULT_FAILED = 1000;

    private TextView mTitleTextView;
    private TextView mCancel;
    private TextView mDone;
    private FileOperator.Operation mOperation;
    private RelativeLayout mBottomSheet;
    private TextView mBackupText;
    private ViewGroup mTopBar;
    private ViewGroup mButtonContainer;
    private RclExpansionHelper mExpansionHelper;
    private boolean mSheetDragging;
    private Rect mTopBarRect = new Rect();
    private Rect mButtonContainerRect = new Rect();
    private boolean mTopBarPressed;
    private boolean mIsValidTopBarTouchDown;
    private boolean mButtonHandling = false;
    private boolean mExpandState = false;
    private MultiWindowMgr mMultiWindowMgr;
    private View mFileSelectedContainer;
    private int mFileSelectedContainerHeight;
    private int mShrinkHeight;
    private ListenerMgr mListenerMgr;
    private boolean mIsSetupBottomSheet = false;
    private MotionEvent mActionDownEvent;
    private boolean mBodyPressed;
    private int mOriginalListCount;
    private Context mContext;
    public static SparseBooleanArray mBottomSheetDragMap = new SparseBooleanArray();

    private boolean isRecreationByPowerSavingPolicy(Bundle bundle) {
        return (bundle != null && UiUtils.isUPSM(mContext));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(this, "onCreate() - " + savedInstanceState);
        super.onCreate(savedInstanceState);
        mContext = getApplicationContext();
        if (isRecreationByPowerSavingPolicy(savedInstanceState)) {
            Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
            if (intent != null) {
                startActivity(intent);
            }
            finish();
            return;
        }
        mMultiWindowMgr = MultiWindowMgr.getInstance(this, getProcessId());
        mMultiWindowMgr.addStateChangeListener(this);
        ensureViews();
        mFileSelectedContainerHeight = (int) getResources().getDimension(R.dimen.file_operation_view_height);
        mShrinkHeight = getWindowHeight() * 60 / 100;
        mExpansionHelper = new RclExpansionHelper();
        mExpansionHelper.setActivity(this);
        mExpansionHelper.setRootView(findViewById(R.id.bottom_sheet));
        mExpansionHelper.setExpansionStatusListener(this);
        mExpansionHelper.enable(R.id.bottom_sheet, mShrinkHeight, RclExpansionHelper.EXPANSION_HEIGHT_AUTO);
        mExpansionHelper.setExpansionMode(RclExpansionHelper.EXPANSION_ADJUST_RESIZE);
        mExpansionHelper.setFixedHeight(mShrinkHeight);
        mExpansionHelper.enableFlingToClose(true);
        mIsSetupBottomSheet = true;
        initViews();
        if (AppFeatures.isTablet()) {
            updateWindowWidth();
            updateActionBar();
        }

        mListenerMgr = new ListenerMgr();
        mListenerMgr.addListener(new SystemBroadcastReceiver(mContext, this, ListenerMgr.LifeCycle.CREATE, ListenerMgr.LifeCycle.DESTROY));
        mListenerMgr.notifyCreate();
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void updateWindowWidth() {
        Window win = getWindow();
        win.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        WindowManager.LayoutParams wlp = win.getAttributes();
        wlp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
        int pickerPopupWidth = (int) getResources().getDimension(R.dimen.picker_popup_width);
        if (pickerPopupWidth < metrics.widthPixels) {
            wlp.width = pickerPopupWidth;
        } else {
            wlp.width = metrics.widthPixels;
        }
        win.setAttributes(wlp);
    }

    @Override
    protected void onHandleStart() {
        Intent intent = getIntent();
        String strStorageType = intent.getStringExtra(EXTRA_KEY_STORAGE_TYPE);
        String path = intent.getStringExtra(EXTRA_KEY_START_PATH);
        String strNavigationMode = intent.getStringExtra(EXTRA_KEY_NAVIGATION_MODE);
        int previousScreenPath = intent.getIntExtra(EXTRA_KEY_PREV_SCREEN_PATH, -1);
        mOriginalListCount = intent.getIntExtra(EXTRA_KEY_TOTAL_COUNT, -1);
        FileRecord.StorageType storageType = FileRecord.StorageType.Local;
        NavigationInfo.NavigationMode navigationMode = NavigationInfo.NavigationMode.Select_destination_path;

        if (!TextUtils.isEmpty(strStorageType)) {
            storageType = FileRecord.StorageType.valueOf(strStorageType);
        }
        if (TextUtils.isEmpty(path)) {
            path = AppConstants.StoragePath.INTERNAL_ROOT;
        }
        if (!TextUtils.isEmpty(strNavigationMode)) {
            navigationMode = NavigationInfo.NavigationMode.valueOf(strNavigationMode);
        }

        FileRecord record = FileRecord.createFileRecord(storageType, path);
        NavigationInfo info = NavigationInfo.getInstance(navigationMode, record);
        info.setControlSelectedFileBoxVisibilityManually(true);
        mNavigationManager.setFromPrivateStorage(intent.getBooleanExtra(EXTRA_KEY_FROM_PRIVATE_STORAGE, false));
        mNavigationManager.setFromPrivateBox(intent.getBooleanExtra(EXTRA_KEY_FROM_PRIVATE_BOX, false));
        SamsungAnalyticsLog.ScreenPath screenPath;
        if (previousScreenPath == SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_LARGE.getCode()) {
            screenPath = SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_LARGE_BACK_UP;
        } else if (previousScreenPath == SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_UNUSED.getCode()) {
            screenPath = SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_UNUSED_BACK_UP;
        } else {
            screenPath = (info.getNavigationMode() == NavigationInfo.NavigationMode.Select_copy_destination) ?
                    SamsungAnalyticsLog.ScreenPath.COPY : SamsungAnalyticsLog.ScreenPath.MOVE;
        }
        info.setScreenPath(screenPath);
        mNavigationManager.enter(info);
    }

    private void ensureViews() {
        ensureActionBarChild();
        mBottomSheet = (RelativeLayout) findViewById(R.id.bottom_sheet);
        mBackupText = (TextView) findViewById(R.id.backup_to_text);
        mTopBar = (ViewGroup) findViewById(R.id.top_bar);
        mFileSelectedContainer = findViewById(R.id.file_selected_container);
        if (AppFeatures.isExtendedScreen(mContext)) {
            RelativeLayout bottomSheetBg = (RelativeLayout) findViewById(R.id.bottom_sheet_bg);
            bottomSheetBg.setBackgroundResource(R.drawable.bottom_sheet_list_bg_extended);
        }
    }

    private void ensureActionBarChild() {
        mButtonContainer = (ViewGroup) findViewById(R.id.btns);
        mTitleTextView = (TextView) findViewById(R.id.actionbar_title);
        mCancel = (TextView) findViewById(R.id.left_btn);
        mDone = (TextView) findViewById(R.id.right_btn);
    }

    private int getActionBarHeight() {
        final DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);

        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true);
        return (int) typedValue.getDimension(metrics);
    }

    private void initViews() {
        Intent intent = getIntent();
        mOperation = FileOperator.Operation.valueOf(intent.getStringExtra(EXTRA_KEY_OPERATION));

        initActionBar();
        initBackupText();

        int windowHeight = getWindowHeight();
        int sheetHeight = mShrinkHeight;
        if (needSheetDragging()) {
            setFileSelectedContainerBottomMargin(-mFileSelectedContainerHeight);
            mExpansionHelper.setTopSpacing(getStatusBarHeight());
            showSelectedFileBox();
        } else {
            mExpansionHelper.setTopSpacing(getActionBarHeight());
            sheetHeight = windowHeight;
            setFullSheet();
        }

        // start animation
        Log.d(this, "start animation: window height=" + windowHeight + ", target height=" + (windowHeight - sheetHeight));
        if (AppFeatures.isTablet()) {
            if (!mMultiWindowMgr.isMultiWindow()) {
                ViEffectMgr.getInstance().startBottomSheet(mBottomSheet, sheetHeight);
            } else {
                //no animation
            }
        } else {
            ViEffectMgr.getInstance().startBottomSheet(mBottomSheet, sheetHeight);
        }
    }

    private void initBackupText() {
        if (mOperation == FileOperator.Operation.BACKUP) {
            boolean canUseNetwork = CloudGatewaySignInUtils.getInstance(mContext).getWifiOnlyMode() ?
                    UiUtils.isWifiOn(mContext) : UiUtils.isNetworkOn(mContext);
            boolean canPerformBackup = StorageMonitor.isSdCardMounted() ||
                    (canUseNetwork &&
                            (CloudMgr.getInstance(this).isSignedIn(FileRecord.CloudType.GoogleDrive) ||
                                    CloudMgr.getInstance(this).isSignedIn(FileRecord.CloudType.SamsungDrive)));
            if (canPerformBackup) {
                mBackupText.setVisibility(View.GONE);
            } else {
                mBackupText.setVisibility(View.VISIBLE);
                if (!UiUtils.supportCloudGateway(mContext)) {
                    mBackupText.setText(R.string.optimize_storage_back_up_to_sdcard_message);
                }
            }
        } else {
            mBackupText.setVisibility(View.GONE);
        }
    }

    private void initActionBar() {
        String title;
        switch (mOperation) {
            case COPY:
                title = getString(R.string.copy_to);
                break;
            case MOVE:
            case REMOVE_FROM_PRIVATE:
                title = getString(R.string.move_to);
                break;
            case BACKUP:
                title = getString(R.string.backup_to);
                break;
            default:
                Log.e(this, "Unsupported operation");
                return;
        }

        if (mTitleTextView != null) {
            mTitleTextView.setText(title);
            UiUtils.limitLargeTextSize(mContext, mTitleTextView);
            setContentDescriptionForActionBar(false);
        }

        if (mDone != null) {
            mDone.setOnClickListener(this);
            mDone.setOnTouchListener(mButtonContainerTouchListener);
            UiUtils.limitLargeTextSize(mContext, mDone);
            UiUtils.setBtnBackgroundColor(mContext, mDone);
            NavigationInfo curInfo = mNavigationManager.getCurInfo();
            if (curInfo != null && curInfo.getStorageType().equals(FileRecord.StorageType.Home)) {
                mDone.setEnabled(false);
            }
            if (UiUtils.isTalkBackEnabled(this)) {
                mDone.setContentDescription(UiUtils.getHomeDescription(this, R.string.menu_done, R.string.button));
            }
        }

        if (mCancel != null) {
            mCancel.setOnClickListener(this);
            mCancel.setOnTouchListener(mButtonContainerTouchListener);
            UiUtils.limitLargeTextSize(mContext, mCancel);
            UiUtils.setBtnBackgroundColor(mContext, mCancel);
            if (UiUtils.isTalkBackEnabled(this)) {
                mCancel.setContentDescription(UiUtils.getHomeDescription(this, R.string.cancel, R.string.button));
            }
        }
    }

    private void setContentDescriptionForActionBar(boolean isExpanded) {
        if (UiUtils.isTalkBackEnabled(this)) {
            if (needSheetDragging()) {
                if (isExpanded) {
                    mTitleTextView.setContentDescription(mTitleTextView.getText() + ", " + getString(R.string.collapse));
                } else {
                    mTitleTextView.setContentDescription(mTitleTextView.getText() + ", " + getString(R.string.expand));
                }
            } else {
                mTitleTextView.setContentDescription(mTitleTextView.getText());
            }
        }
    }

    private int getWindowHeight() {
        int result;
        boolean isMultiWindow = mMultiWindowMgr.isMultiWindow();
        boolean isScaleWindow = mMultiWindowMgr.isScaleWindow();
        Log.d(this, "window state : " + isMultiWindow + ", " + isScaleWindow);
        if (!isMultiWindow || isScaleWindow) {
            Display display = getWindowManager().getDefaultDisplay();
            Point point = new Point();
            display.getSize(point);
            result = point.y;
        } else {
            result = mMultiWindowMgr.getRectInfo().height();
        }
        return result;
    }

    @Override
    protected void onResume() {
        Log.d(this, "onResume()");
        super.onResume();
        if (!mIsSetupBottomSheet) {
            mExpansionHelper.setup();
            mIsSetupBottomSheet = true;
        }
        hideStatusBar();
    }

    private void updateActionBar() {
        if (!mMultiWindowMgr.isMultiWindow()) {
            int topSpacing = getStatusBarHeight();
            mExpansionHelper.setTopSpacing(topSpacing);
            mTopBar.setBackground(getResources().getDrawable(R.drawable.bottom_sheet_handle_background));
        } else {
            mExpansionHelper.setTopSpacing(0);
            mTopBar.setBackground(getResources().getDrawable(R.drawable.actionbar_bg));
        }
    }

    private void hideStatusBar() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        hideStatusBar();
    }

    @Override
    protected void onPause() {
        Log.d(this, "onPause()");
        super.onPause();
        mIsSetupBottomSheet = false;
        overridePendingTransition(0, 0);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        mTopBar.getGlobalVisibleRect(mTopBarRect);
        mButtonContainer.getGlobalVisibleRect(mButtonContainerRect);
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                if (isTopBarEvent(event)) {
                    mTopBarPressed = true;
                    if (!mExpansionHelper.isLocked()) {
                        mIsValidTopBarTouchDown = true;
                    }
                } else {
                    mActionDownEvent = MotionEvent.obtain(event);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mIsValidTopBarTouchDown && isTopBarEvent(event)) {
                    mIsValidTopBarTouchDown = false;
                    mExpansionHelper.setExpansion(!mExpansionHelper.isExpanded());
                }
                finishSheetDrag(event);
                break;
            case MotionEvent.ACTION_MOVE:
                if (!mTopBarPressed && !mExpansionHelper.isLocked() && mActionDownEvent != null) {
                    float prevY = mActionDownEvent.getY();
                    float currentY = event.getY();
                    // ignore clicking and staying in ACTION_DOWN position.
                    if (Math.abs(currentY - prevY) > 20) {
                        if (!mExpansionHelper.isExpanded() ||
                                (currentY > prevY && isContentsAtTop())) {
                            mExpansionHelper.onTouchEvent(mActionDownEvent);
                            mBodyPressed = true;
                        }
                        mActionDownEvent = null;
                        if (mBodyPressed) {
                            MotionEvent e = MotionEvent.obtain(event);
                            e.setAction(MotionEvent.ACTION_CANCEL);
                            super.dispatchTouchEvent(e);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                finishSheetDrag(event);
                break;
        }
        if (mTopBarPressed || mSheetDragging || mBodyPressed) {
            return mExpansionHelper.onTouchEvent(event);
        } else {
            return super.dispatchTouchEvent(event);
        }
    }

    private boolean isContentsAtTop() {
        boolean ret = false;
        NavigationInfo info = NavigationManager.getInstance(getProcessId()).getCurInfo();
        if (info != null) {
            AbsMyFilesFragment curFragment = info.getCurFragment();
            if (curFragment instanceof HomeFragment) {
                ret = ((HomeFragment) curFragment).isContentsAtTop();
            } else if (curFragment instanceof FileListFragment) {
                AbsListView listView = curFragment.getListView();
                if (listView != null) {
                    ret = listView.getChildCount() == 0 ||
                            listView.getChildAt(0).getTop() >= 0;
                }
            }
        }
        return ret;
    }

    private boolean isTopBarEvent(MotionEvent event) {
        int rawX = (int) event.getX();
        int rawY = (int) event.getY();
        return !mButtonHandling &&
                !mButtonContainerRect.contains(rawX, rawY) &&
                mTopBarRect.contains(rawX, rawY);
    }

    private void finishSheetDrag(MotionEvent event) {
        mExpansionHelper.onTouchEvent(event);
        if (mTopBarPressed) {
            mTopBarPressed = false;
        }
        if (mBodyPressed) {
            mBodyPressed = false;
            mActionDownEvent = null;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int windowHeight = getWindowHeight();
        mExpansionHelper.updateHeights(windowHeight, (int) (windowHeight * 0.6));
        setExpansionOfBottomSheet();
        if (AppFeatures.isTablet()) {
            updateWindowWidth();
            updateActionBar();
            hideStatusBar();
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
    }

    private void setExpansionOfBottomSheet() {
        if (needSheetDragging()) {
            mExpansionHelper.setTopSpacing(getStatusBarHeight());
            lockSheet(false);
            if (!mExpandState) {
                mExpansionHelper.setExpansion(false);
                setFileSelectedContainerBottomMargin(-mFileSelectedContainerHeight);
            }
        } else {
            int topSpacing = mTopBar.getHeight();
            mExpansionHelper.setTopSpacing(topSpacing);
            setFullSheet();
        }
    }

    @Override
    public void onClick(View v) {
        int processId = getProcessId();
        if (v.equals(mDone)) {
            Log.a(this, "[Done]");

            NavigationInfo curInfo = NavigationManager.getInstance(processId).getCurInfo();
            if (mOperation == FileOperator.Operation.BACKUP) {
                ArrayList<FileRecord> selectedList = CopyMoveCmd.getSelectedList();
                if (selectedList != null) {
                    long value = selectedList.size();
                    String detail = String.valueOf(mOriginalListCount);
                    SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.DONE, value, detail, null);
                    MyFilesFacade.deleteRecord(processId, this, curInfo.getCurFragment(), selectedList,
                            DeleteRecordCmd.OperationProgress.SHOW_OPTIMIZE_STORAGE_DELETE_CONFIRM_POPUP);
                }
                return;
            }

            SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.DONE, null);
            boolean srcToBeDeleted = false;
            CopyMoveCmd.setRemoveFromPrivateOperation(false);
            if (FileOperator.Operation.MOVE.equals(mOperation)) {
                srcToBeDeleted = true;
            } else if (FileOperator.Operation.REMOVE_FROM_PRIVATE.equals(mOperation)) {
                srcToBeDeleted = true;
                CopyMoveCmd.setRemoveFromPrivateOperation(true);
            }
            setResultAndFinish(srcToBeDeleted);
        } else if (v.equals(mCancel)) {
            Log.a(this, "[Cancel]");
            SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.CANCEL, null);
            setResult(RESULT_CANCELED);
        }
        closeSheet();
    }

    public void setResultAndFinish(boolean srcToBeDeleted) {
        Intent data = new Intent();
        String resultPath = null;
        String storageType = null;
        NavigationInfo curInfo = NavigationManager.getInstance(getProcessId()).getCurInfo();
        if (curInfo != null) {
            FileRecord curRecord = curInfo.getCurRecord();
            if (curRecord != null) {
                resultPath = curRecord.getFullPath();
                storageType = curRecord.getStorageType().name();
                if (curRecord.getStorageType() == FileRecord.StorageType.Cloud) {
                    getCloudInfo(((CloudFileRecord) curRecord), data);
                }
            }
        }
        if (TextUtils.isEmpty(resultPath) || TextUtils.isEmpty(storageType)) {
            setResult(RESULT_FAILED);
        } else {
            if (srcToBeDeleted) {
                mOperation = FileOperator.Operation.MOVE;
            } else {
                mOperation = FileOperator.Operation.COPY;
            }
            data.putExtra(EXTRA_KEY_OPERATION, mOperation.name());
            data.putExtra(EXTRA_KEY_STORAGE_TYPE, storageType);
            data.putExtra(EXTRA_KEY_DESTINATION_PATH, resultPath);
            setResult(RESULT_OK, data);
        }
        closeSheet();
    }

    private void getCloudInfo(CloudFileRecord curRecord, Intent data) {
        data.putExtra(EXTRA_KEY_CLOUD_FILE_ID, curRecord.getFileId());
        data.putExtra(EXTRA_KEY_CLOUD_DEVICE_ID, curRecord.getDeviceId());
        data.putStringArrayListExtra(EXTRA_KEY_CLOUD_PARENT_IDS, curRecord.getParentIds());
        data.putExtra(EXTRA_KEY_FILE_TYPE, curRecord.getFileType());
    }

    @Override
    public void onBackPressed() {
        Log.a(this, "back_key");
        NavigationManager navigationManager = NavigationManager.getInstance(getProcessId());
        if (navigationManager.getDepth() > 1) {
            navigationManager.leave(this);
        } else {
            if (needSheetDragging() && mExpansionHelper.isExpanded()) {
                mExpansionHelper.setExpansion(false);
            } else {
                setResult(RESULT_CANCELED);
                closeSheet();
            }
        }
    }

    private void closeSheet() {
        NavigationInfo curInfo = NavigationManager.getInstance(getProcessId()).getCurInfo();
        if (curInfo != null) {
            AbsMyFilesFragment fragment = curInfo.getCurFragment();
            if (fragment != null) {
                fragment.clearObserver();
            }
        }
        if (AppFeatures.isTablet()) {
            if (!mMultiWindowMgr.isMultiWindow()) {
                mExpansionHelper.close(true);
            } else {
                finish();
            }
        } else {
            mExpansionHelper.close(true);
        }
    }

    @Override
    public void onStart(boolean isExpanded) {
        Log.d(this, "onStart():" + isExpanded);
        mSheetDragging = true;
        setContentDescriptionForActionBar(isExpanded);
        if (isExpanded) {
            SamsungAnalyticsLog.sendLog(getProcessId(), SamsungAnalyticsLog.Event.EXPAND_PANEL, null);
        }
        mBottomSheetDragMap.put(getProcessId(), mSheetDragging);
    }

    @Override
    public void onProgress(int progress) {
        if (mIsValidTopBarTouchDown) {
            mIsValidTopBarTouchDown = false;
        }
        setFileSelectedContainerBottomMargin(
                (int) (-mFileSelectedContainerHeight + (mFileSelectedContainerHeight * progress / 100.0f)));
    }

    @Override
    public void onFinish(boolean isExpanded) {
        Log.d(this, "onFinish():" + isExpanded);
        mSheetDragging = false;
        if (!needSheetDragging()) {
            lockSheet(true);
        }
        mBottomSheetDragMap.put(getProcessId(), mSheetDragging);
    }

    @Override
    public void onClose() {
        Log.d(this, "onClose()");
        finish();
    }

    @Override
    public void onMaxHeightChanged(int maxHeight) {
    }

    @Override
    public void onModeChanged() {
        if (needSheetDragging()) {
            lockSheet(false);
        } else {
            setFullSheet();
        }
    }

    @Override
    public void onZoneChanged() {
    }

    @Override
    public void onSizeChanged(Rect rectInfo) {
    }

    @Override
    public void onNavigationChanged(NavigationInfo preInfo, NavigationInfo curInfo) {
        super.onNavigationChanged(preInfo, curInfo);
        if (curInfo != null) {
            if (mDone != null) {
                boolean enable = curInfo.getStorageType() != FileRecord.StorageType.Home;
                mDone.setEnabled(enable);
                mDone.setFocusable(enable);
            }
        }
    }

    private void setFileSelectedContainerBottomMargin(int bottomMargin) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mFileSelectedContainer.getLayoutParams();
        lp.bottomMargin = bottomMargin;
    }

    private void setFullSheet() {
        showSelectedFileBox();
        setFileSelectedContainerBottomMargin(0);
        mExpansionHelper.setExpansion(true, false);
    }

    private void showSelectedFileBox() {
        if (mFileSelectedContainer != null) {
            mFileSelectedContainer.setVisibility(View.VISIBLE);
        }
    }

    private boolean needSheetDragging() {
        int orientation = getResources().getConfiguration().orientation;
        boolean ret = (!mMultiWindowMgr.isMultiWindow() || mMultiWindowMgr.isScaleWindow()) &&
                orientation == Configuration.ORIENTATION_PORTRAIT;
        Log.d(this, "needSheetDragging(): " + orientation + ", " + ret);
        return ret;
    }

    private void lockSheet(boolean lock) {
        if (lock) {
            mExpansionHelper.lock();
        } else {
            mExpansionHelper.unlock();
        }
    }

    private View.OnTouchListener mButtonContainerTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    mButtonHandling = true;
                    break;

                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    mButtonHandling = false;
                    break;
            }
            return false;
        }
    };

    @Override
    protected void onDestroy() {
        Log.d(this, "onDestroy");
        if (mMultiWindowMgr != null) {
            mMultiWindowMgr.removeStateChangeListener(this);
            mMultiWindowMgr = null;
        }
        if (mDone != null) {
            mDone.setOnClickListener(null);
            mDone.setOnTouchListener(null);
        }
        if (mCancel != null) {
            mCancel.setOnClickListener(null);
            mCancel.setOnTouchListener(null);
        }
        mButtonContainerTouchListener = null;
        if (mExpansionHelper != null) {
            mExpansionHelper.setExpansionStatusListener(null);
            mExpansionHelper.onDestroy();
        }
        super.onDestroy();
        if (mListenerMgr != null) {
            mListenerMgr.notifyDestroy();
        }
        mBottomSheetDragMap.delete(getProcessId());
    }

    @Override
    public void onMediaEject(String path) {
        String selectedPath;
        ArrayList<FileRecord> selectedItems = CopyMoveCmd.getSelectedList();
        if (selectedItems == null) {
            return;
        }
        for (FileRecord record : selectedItems) {
            if (record != null) {
                selectedPath = record.getFullPath();
                if (selectedPath != null && selectedPath.startsWith(path)) {
                    closeSheet();
                    break;
                }
            }
        }
    }

}
